<?php
/**
 * Created by PhpStorm.
 * Script Name: Fm.php
 * Create: 2023/6/6 8:20
 * Description:
 * Author: fudaoji<fdj@kuryun.cn>
 */

namespace addons\fhelper\common\library;


class Fm
{
    /**
     * Clean path
     * @param string $path
     * @param bool $trim
     * @return string
     */
    static function cleanPath($path, $trim = true)
    {
        $path = $trim ? trim($path) : $path;
        $path = trim($path, '\\/');
        $path = str_replace(array('../', '..\\'), '', $path);
        $path =  self::getAbsolutePath($path);
        if ($path == '..') {
            $path = '';
        }
        return str_replace('\\', '/', $path);
    }

    /**
     * Path traversal prevention and clean the url
     * It replaces (consecutive) occurrences of / and \\ with whatever is in DIRECTORY_SEPARATOR, and processes /. and /.. fine.
     * @param $path
     * @return string
     */
    static function getAbsolutePath($path) {
        $path = str_replace(array('/', '\\'), DIRECTORY_SEPARATOR, $path);
        $parts = array_filter(explode(DIRECTORY_SEPARATOR, $path), 'strlen');
        $absolutes = array();
        foreach ($parts as $part) {
            if ('.' == $part) continue;
            if ('..' == $part) {
                array_pop($absolutes);
            } else {
                $absolutes[] = $part;
            }
        }
        return implode(DIRECTORY_SEPARATOR, $absolutes);
    }
}